from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, Body
from sqlalchemy.orm import Session
from typing import Optional
from pydantic import BaseModel
import time

from backend.app.database.session import get_db
from backend.app.services.requirements_service import optimize_requirements, optimize_requirements_from_file
from backend.app.utils.file_utils import save_upload_file
from backend.app.database.models import Requirement, Activity

router = APIRouter()


# 定义请求模型
class RequirementOptimizeRequest(BaseModel):
    content: str
    title: Optional[str] = "需求优化"
    user_id: Optional[int] = 1


"""优化文本需求"""


@router.post("/requirements/optimize")
async def optimize_req(
        request: RequirementOptimizeRequest = Body(...),
        db: Session = Depends(get_db)
):
    """优化文本需求"""
    try:
        start_time = time.time()
        # 添加 model_type 参数并获取 model_used 返回值
        optimized, processing_time, model_used = optimize_requirements(request.content,
                                                                       request.model_type if hasattr(request,
                                                                                                     'model_type') else None)
        processing_time = time.time() - start_time

        # 保存到数据库
        requirement = Requirement(
            title=request.title,
            original_content=request.content,
            optimized_content=optimized,
            user_id=request.user_id,
            processing_time=processing_time,
            model_used=model_used  # 保存使用的模型
        )
        db.add(requirement)

        # 记录活动
        activity = Activity(
            user_id=request.user_id,
            activity_type="requirement_optimization",
            description=f"优化了{request.title}需求"
        )
        db.add(activity)
        db.commit()

        return {
            "success": True,
            "data": {
                "original": request.content,
                "optimized": optimized,
                "processing_time": processing_time,
                "model_used": model_used
            }
        }
    except Exception as e:
        import traceback
        db.rollback()
        raise HTTPException(status_code=500, detail=str(traceback.format_exception(type(e), e, e.__traceback__)))


"""从文件优化需求"""


@router.post("/requirements/optimize-file")
async def optimize_req_file(
        file: UploadFile = File(...),
        title: str = Form("文件需求优化"),
        user_id: int = Form(1),  # 默认用户ID，实际应从认证中获取
        model_type: Optional[str] = Form(None),  # 添加 model_type 参数
        db: Session = Depends(get_db)
):
    """从文件优化需求"""
    try:
        # 保存上传文件
        file_path = await save_upload_file(file)

        start_time = time.time()
        # 添加 model_type 参数并获取 model_used 返回值
        original_content, optimized, processing_time, model_used = optimize_requirements_from_file(file_path,
                                                                                                   file.filename,
                                                                                                   model_type)
        processing_time = time.time() - start_time

        # 保存到数据库
        requirement = Requirement(
            title=title,
            original_content=original_content,
            optimized_content=optimized,
            user_id=user_id,
            processing_time=processing_time,
            model_used=model_used  # 保存使用的模型
        )
        db.add(requirement)

        # 记录活动
        activity = Activity(
            user_id=user_id,
            activity_type="requirement_optimization",
            description=f"优化了{file.filename}需求"
        )
        db.add(activity)
        db.commit()

        return {
            "success": True,
            "data": {
                "filename": file.filename,
                "original": original_content,
                "optimized": optimized,
                "processing_time": processing_time,
                "model_used": model_used
            }
        }
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))
